package com.sanhuo.utils.basic;

import java.lang.reflect.Field;


/**
 * @author zzs
 * @version 1.0
 * @describe 实体工具类
 * @createTime 2018.1.5
 */
public class BeanUtil {
    /**
     * 将T中的跟D同名字段的字段的值赋到D上
     *
     * @param t
     * @param d
     * @param <T>
     * @param <D>
     */
    public static <T, D> void copyBean(T t, D d) throws IllegalAccessException {

        Field[] TList = getNotNullEntityFieldList(t);
        Field[] DList = getNotNullEntityFieldList(d);
        for (Field field : TList) {
            field.setAccessible(true);
            if (field.get(t) != null) {
                field.setAccessible(true);
                for (Field field1 : DList) {
                    copyField(field, field1, t, d);
                }
            }
        }
    }

    /**
     * 不复制FieldNames
     *
     * @param t
     * @param d
     * @param fieldNames
     * @param <T>
     * @param <D>
     */
    public static <T, D> void copyBeanIgnore(T t, D d, String... fieldNames) throws IllegalAccessException {
        Field[] TList = getNotNullEntityFieldList(t);
        Field[] DList = getNotNullEntityFieldList(d);
        for (Field field : TList) {
            field.setAccessible(true);
            if (field.get(t) != null)
                for (Field field1 : DList) {
                    boolean canCopy = true;
                    for (String fieldName : fieldNames) {
                        canCopy = canCopy && (!fieldName.equals(field.getName())) && (!fieldName.equals(field1.getName()) && field.getName().equals(field1.getName()));
                    }
                    if (canCopy) {
                        copyField(field, field1, t, d);
                    }
                }
        }
    }


    private static <T, D> void copyField(Field field, Field field1, T t, D d) {
        if (field.getName().equals(field1.getName())) {
            field1.setAccessible(true);
            try {
                field1.set(d, field.get(t));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 判断实体类不为空再获取字段列表
     *
     * @param t
     * @param <T>
     * @return
     */
    private static <T> Field[] getNotNullEntityFieldList(T t) {
        isNull(t);
        return ReflectionUtil.getFieldList(t);
    }


    public static Boolean isNull(Object o) {
        return o == null || "".equals(o);
    }

    public static Boolean isNotNull(Object o) {
        return !(o == null || "".equals(o));
    }

}
